package com.mall.b2c.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mall.b2c.service.*;
import com.mall.common.validation.annotation.RequiredStringValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.domain.order.OrderDomain;
import com.mall.b2c.domain.order.ShippingDomain;
import com.mall.b2c.enums.OrderStatus;
import com.mall.b2c.enums.PayStatus;
import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.b2c.util.ShopUtil;
import com.mall.common.bean.Message;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.bean.SearchFilter.Operator;
import com.mall.common.controller.BaseAuthController;
import com.mall.common.domain.AreaDomain;
import com.mall.common.enums.PayType;
import com.mall.common.exception.ApplicationException;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.AreaService;
import com.mall.common.service.PaymentTypeService;
import com.mall.common.util.EnumUtils;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;

/**
 * 后台Action类 - 订单
 */
@Controller
@RequestMapping("/admin/b2c/order")
public class OrderController extends BaseAuthController {

	@Resource private OrderService orderService;
	@Resource private PaymentTypeService paymentTypeService;
	@Resource private OrderItemService orderItemService;
    @Resource private DeliveryMethodService deliveryMethodService;
    @Resource private DeliveryCenterService deliveryCenterService;
    @Resource private AreaService areaService;
    @Resource private ShippingService shippingService;
    @Resource private RefundService refundService;
	@Resource private StoreService storeService;

	/**
	 * 跳转到列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		model.addAttribute("orderStatusList",
				EnumUtils.enumProp2I18nList(OrderStatus.class));
		model.addAttribute("payTypeList",
				EnumUtils.enumProp2I18nList(PayType.class));
		model.addAttribute("payStatusList",
				EnumUtils.enumProp2I18nList(PayStatus.class));

		model.addAttribute("storeList", storeService.getAll());

		return "/admin/b2c/order/list";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/queryData", method = RequestMethod.POST)
	@ResponseBody
	public Pager queryData(Pager pager, HttpServletRequest request) {
		Map<String, Object> filterParams = Servlets
				.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
		filters.add(new SearchFilter("isDelete", Operator.EQ, false));
		pager = orderService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
	}

	/**
	 * 跳转到详情
	 */
	@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "id", message = "订单不存在") })
	@RequestMapping(value = "/detail")
	public String detail(Long id, Model model) {
		OrderDomain order = orderService.find(id);
		if (order == null) {
			throw new NoticeException("订单不存在");
		}
		buttonAuth("audit", "/admin/order/audit*", model);
		buttonAuth("confirm", "/admin/order/confirm*", model);
		buttonAuth("pick", "/admin/order/pick*", model);
		buttonAuth("payment", "/admin/order/payment*", model);
		buttonAuth("shipping", "/admin/order/shipping*", model);
		buttonAuth("complete", "/admin/order/complete*", model);
		buttonAuth("refund", "/admin/order/refund*", model);
		buttonAuth("cancel", "/admin/order/cancel*", model);
		model.addAttribute("order", order);
		return "/admin/b2c/order/detail";
	}

	/**
	 * 拣货
	 */
	@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "orderId", message = "订单不存在") })
	@RequestMapping(value = "/pickup", method = RequestMethod.POST)
	public String pickup(Long orderId) {
		orderService.pickup(orderId, ShopUtil.getUser().getUsername());
		return "redirect:detail.jhtml?id=" + orderId;
	}

	/**
	 * 完成订单
	 */
	@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "orderId", message = "ID非法") })
	@RequestMapping(value = "/complete", method = RequestMethod.POST)
	public String complete(Long orderId, HttpServletResponse response) {
		orderService.complete(orderId, ShopUtil.getUser().getUsername());
		return "redirect:detail.jhtml?id=" + orderId;
	}

	/**
	 * 删除
	 */
	@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "ids", message = "订单不存在!") })
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public String delete(Long[] ids, HttpServletResponse response) {
		orderService.delete(ids, ShopUtil.getUser().getUsername());
		return ResponseUtils.renderJSON(successMessage, response);
	}

	/**
	 * 取消订单
	 */
	@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "orderNo", message = "订单编号为空") })
	@RequestMapping(value = "/cancel", method = RequestMethod.POST)
	public String cancel(String orderNo, HttpServletResponse response) {
		try {
			orderService.cancel(orderNo, ShopUtil.getUser().getUsername());
		} catch (ApplicationException e) {
			return ResponseUtils.renderJSON(
					Message.error(e.getMessage(), null), response);
		}
		return ResponseUtils.renderJSON(successMessage, response);
	}

	/**
	 * 订单项列表
	 */
	@RequestMapping(value = "/items", method = RequestMethod.GET)
	public String items(Long id, Model model) {
		model.addAttribute("id", id);
		return "/admin/b2c/order/items";
	}

	/**
	 * 指定订单项列表分页数据
	 */
	@Validations(requiredFields = { 
			@RequiredFieldValidator(fieldName = "id", message = "订单不存在!") 
	})
	@RequestMapping(value = "/queryOrderItem", method = RequestMethod.POST)
	@ResponseBody
	public Pager queryOrderItem(Pager pager, Long id) {
		if (pager == null) {
			pager = new Pager();
		}
		pager.addSearchFilter(new SearchFilter("order.id", Operator.EQ, id));
		pager = orderItemService.findPage(pager);
		return JsonDataGridHelper.createJSONData(pager);
	}
	
	/**
	 * 发货
	 * @return
	 */
	@RequestMapping(value="/shipping", method=RequestMethod.GET)
	public String shipping(Long orderId, Model model){
		OrderDomain order = orderService.find(orderId);
		if(order == null){
			throw new NoticeException("订单不存在");
		}
		if(order.getOrderStatus() != OrderStatus.waitSellerSendGoods && order.getAllShiped()){
			throw new NoticeException("当前订单状态不能进行发货操作");
		}
		model.addAttribute("order", order);
		AreaDomain area = areaService.find(order.getAreaId());
		model.addAttribute("area", area);
		model.addAttribute("deliveryMethodList", deliveryMethodService.getAll());
		model.addAttribute("deliveryCenterList", deliveryCenterService.getAll());
		return "/admin/b2c/order/shipping";
	}
	
	/**
	 * 发货
	 * @return
	 */
	@Validations(requiredFields = { 
			@RequiredFieldValidator(fieldName = "orderId", message = "发货订单不能为空"),
			@RequiredFieldValidator(fieldName = "areaId", message = "收货地区不能为空"),
			@RequiredFieldValidator(fieldName = "logisticsNo", message = "物流单号不能为空"),
			@RequiredFieldValidator(fieldName = "deliveryMethodId", message = "配送方式不能为空"),
			@RequiredFieldValidator(fieldName = "deliveryCenterId", message = "发货点不能为空"),
			@RequiredFieldValidator(fieldName = "shipFee", message = "物流费用不能为空"),
			@RequiredFieldValidator(fieldName = "mobile", message = "手机/电话不能为空"),
			@RequiredFieldValidator(fieldName = "address", message = "地址不能为空"),
			@RequiredFieldValidator(fieldName = "orderItemIds", message = "发货订单项不能为空"),
			@RequiredFieldValidator(fieldName = "quantitys", message = "发货数量不能为空")
	})
	@RequestMapping(value="/shipping", method=RequestMethod.POST)
	public String shipping(ShippingDomain shipping, Long orderId, Long areaId,
			Long[] orderItemIds, Integer[] quantitys,Long deliveryMethodId,
			Long deliveryCenterId, HttpServletResponse response){
		shippingService.shipping(shipping, orderId, areaId, orderItemIds,
				quantitys, deliveryMethodId, deliveryCenterId, ShopUtil.getUser().getUsername());
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	
	/**
	 * 支付
	 * @return
	 */
	@Validations(
		requiredFields={
				@RequiredFieldValidator(fieldName="orderId", message="ID非法")
		}
	)
	@RequestMapping(value="/payment", method=RequestMethod.GET)
	public String toPayment(Long orderId, Model model){
		OrderDomain order = orderService.find(orderId);
		if(order == null || order.getIsExpired()){
			throw new NoticeException("订单不存在或已过期");
		}
		OrderStatus status = order.getOrderStatus();
		if(status.equals(OrderStatus.tradeClosed) 
				|| status.equals(OrderStatus.tradeFinished)){
			throw new NoticeException("当前订单状态无法进行操作");
		}
		
		if(!order.getPayStatus().equals(PayStatus.unpay)){
			throw new NoticeException("该订单已支付过了，请查看支付状态");
		}
		model.addAttribute("order", order);
		model.addAttribute("paymentTypeList", paymentTypeService.getList("available", true)) ;
		return "/admin/b2c/order/payment";
	}
	
	/**
	 * 支付
	 */
	@Validations(
		requiredFields={
				@RequiredFieldValidator(fieldName="orderNo", message="订单编号为空")
		}
	)
	@RequestMapping(value="/payment", method=RequestMethod.POST)
	public String payment(String orderNo, String memo, HttpServletResponse response){
		orderService.offlinePay(orderNo, ShopUtil.getUser().getUsername(), memo);
		return ResponseUtils.renderJSON(successMessage, response);
	}


	/**
	 * 退款申请页面
	 */
	@Validations(
		requiredFields={
				@RequiredFieldValidator(fieldName="orderId", message="订单不存在")
		}
	)
	@RequestMapping(value="/refund", method=RequestMethod.GET)
	public String refund(Long orderId, Model model){
		OrderDomain order = orderService.find(orderId);
		if(order == null || order.getIsExpired()){
			throw new NoticeException("订单不存在或已过期");
		}
		if(order.getOrderStatus() != OrderStatus.waitSellerSendGoods
				&& order.getOrderStatus() != OrderStatus.tradeFinished){
			throw new NoticeException("订单状态不正确");
		}
		model.addAttribute("area", areaService.find(order.getAreaId()));
		model.addAttribute("order", order);
		return "/admin/b2c/order/refund";
	}


	/**
	 * 提交退款申请
	 */
	@Validations(
		requiredFields={
				@RequiredFieldValidator(fieldName="orderId", message="订单不存在"),
				@RequiredFieldValidator(fieldName="itemIds", message="请选择申请退款订单项"),
				@RequiredFieldValidator(fieldName="quantitys", message="申请退款数量不正确"),
				@RequiredFieldValidator(fieldName="isChange", message="请选择是否换货")
		},
		requiredStrings={
				@RequiredStringValidator(fieldName="consignee", message="联系人必填"),
				@RequiredStringValidator(fieldName="contact", message="联系电话必填"),
				@RequiredStringValidator(fieldName="remark", message="备注必填")
		}
	)
	@RequestMapping(value="/refund", method=RequestMethod.POST)
	public String createRefund(Boolean isChange, String consignee, Long areaId,
							   String address, String contact, String remark,
							   Long orderId, Long[] itemIds,
							   Integer[] quantitys, HttpServletResponse response){
		refundService.applyRefundForAdmin(itemIds, quantitys, isChange, consignee, areaId, address, contact, remark, orderId, getUsername());
		return ResponseUtils.renderJSON(successMessage, response);
	}



}
